﻿using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;

namespace Vision.VisionWorkshop.Controls
{
    /// <summary>
    /// A UI-friendly wrapper around a Person object.
    /// </summary>
    public class TypeViewModel :  INotifyPropertyChanged
    {
        readonly ReadOnlyCollection<TypeViewModel> children;
        readonly TypeViewModel parent;
        readonly TypeInfo person;

        bool isExpanded;
        bool isSelected;

        public TypeViewModel(TypeInfo person)
            : this(person, null)
        {
        }

        private TypeViewModel(TypeInfo person, TypeViewModel parent)
        {
            this.person = person;
            this.parent = parent;

            this.children = new ReadOnlyCollection<TypeViewModel>(
                    (from child in this.person.Children
                     select new TypeViewModel(child, this))
                     .ToList<TypeViewModel>());
        }

        public ReadOnlyCollection<TypeViewModel> Children
        {
            get { return this.children; }
        }

        public string MemberName
        {
            get { return this.person.MemberName; }
        }

        public string TypeName
        {
            get { return this.person.TypeName; }
        }

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// associated with this object is expanded.
        /// </summary>
        public bool IsExpanded
        {
            get { return this.isExpanded; }
            set
            {
                if (value != this.isExpanded)
                {
                    this.isExpanded = value;
                    this.OnPropertyChanged("IsExpanded");
                }

                // Expand all the way up to the root.
                if (this.isExpanded && this.parent != null)
                    this.parent.IsExpanded = true;
            }
        }

        /// <summary>
        /// Gets/sets whether the TreeViewItem 
        /// associated with this object is selected.
        /// </summary>
        public bool IsSelected
        {
            get { return this.isSelected; }
            set
            {
                if (value != this.isSelected)
                {
                    this.isSelected = value;
                    this.OnPropertyChanged("IsSelected");
                }
            }
        }

        public TypeViewModel Parent
        {
            get { return this.parent; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}